<template>
  <div class="product-category-container">
    <!-- 页面标题和店铺信息 -->
    <div class="page-header">
      <div class="header-content">
        <h2><i class="el-icon-folder"></i> 商品类目管理</h2>
        <div class="shop-info" v-if="shopId">
          <span class="product-count">共 {{ pagination.total }} 个分类</span>
        </div>
      </div>
    </div>

    <!-- 提示信息 -->
    <el-alert
      v-if="!shopId"
      title="请先登录并获取店铺信息"
      type="warning"
      :closable="false"
      show-icon
      class="mb-4"
    >
      无法获取店铺信息，请检查登录状态或联系管理员
    </el-alert>

    <!-- 搜索筛选区域 -->
    <div class="search-container" :class="{ 'disabled-state': !shopId }">
      <div class="search-form">
        <!-- 将输入框改为下拉选择框 -->
        <el-select
          v-model="searchForm.categoryName"
          placeholder="选择类目名称"
          clearable
          filterable
          class="search-input"
          :disabled="!shopId"
        >
          <el-option
            v-for="item in categoryOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
        
        <el-select 
          v-model="searchForm.categoryStatus" 
          placeholder="状态" 
          clearable
          class="search-input"
          :disabled="!shopId"
        >
          <el-option label="启用" :value="1"></el-option>
          <el-option label="禁用" :value="0"></el-option>
        </el-select>
        
        <el-button 
          type="primary" 
          icon="el-icon-search" 
          @click="handleSearch"
          :disabled="!shopId"
        >搜索</el-button>
        <el-button 
          icon="el-icon-refresh" 
          @click="resetSearch"
          :disabled="!shopId"
        >重置</el-button>
      </div>
      
      <div class="action-buttons">
        <el-button 
          type="primary" 
          icon="el-icon-plus" 
          class="btn-add" 
          @click="handleAdd"
          :disabled="!shopId"
        >新增类目</el-button>
        <el-button 
          type="danger"
          icon="el-icon-remove-outline"
          @click="handleBatchDelete"
          :disabled="!hasDeletePermission || selectedIds.length === 0 || !shopId"
        >
          批量删除 ({{ selectedIds.length }})
        </el-button>
      </div>
    </div>

    <!-- 类目列表 -->
    <div class="table-container" :class="{ 'disabled-state': !shopId }">
      <el-table 
        :data="categoryList" 
        style="width: 100%;"
        ref="table"
        @selection-change="handleSelectionChange"
        v-loading="loading"
        stripe
        border
        :row-class-name="tableRowClassName"
        empty-text="暂无数据或未获取到店铺信息"
      >
        <el-table-column type="selection" width="100" align="center"></el-table-column>
        
        <el-table-column prop="categoryName" label="类目名称" min-width="180" align="center">
          <template slot-scope="scope">
            <div class="category-name">
              <i class="el-icon-folder-opened"></i>
              {{ scope.row.categoryName }}
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="categoryStatus" label="状态" width="100" align="center">
          <template slot-scope="scope">
            <el-tag 
              :type="scope.row.categoryStatus === 1 ? 'success' : 'danger'" 
              size="small"
              :effect="scope.row.categoryStatus === 1 ? 'dark' : 'plain'"
            >
              {{ scope.row.categoryStatus === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="createTime" label="创建时间" width="260" align="center"></el-table-column>
        <el-table-column prop="updateTime" label="更新时间" width="260" align="center"></el-table-column>
        
        <el-table-column label="操作" width="380" fixed="right" align="center">
          <template slot-scope="scope">
            <el-button 
              size="mini" 
              icon="el-icon-edit" 
              @click="handleEdit(scope.row)"
              :disabled="!hasEditPermission"
            >编辑</el-button>
            <el-button 
              size="mini" 
              icon="el-icon-delete" 
              type="danger"
              plain
              @click="handleDelete(scope.row.id)"
              :disabled="!hasDeletePermission"
            >删除</el-button>
            <el-button 
              size="mini" 
              :type="scope.row.categoryStatus === 1 ? 'warning' : 'success'"
              @click="handleStatusChange(scope.row)"
              :disabled="!hasEditPermission"
            >
              {{ scope.row.categoryStatus === 1 ? '禁用' : '启用' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-container" v-if="shopId">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pagination.currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pagination.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
      ></el-pagination>
    </div>

    <!-- 新增/编辑类目弹窗 -->
    <el-dialog 
      :title="formTitle" 
      :visible.sync="dialogVisible"
      width="500px"
      :close-on-click-modal="false"
      custom-class="category-form-dialog"
    >
      <el-form 
        :model="formData" 
        :rules="formRules" 
        ref="categoryFormRef"
        label-width="100px"
        label-position="left"
      >
        <el-form-item label="类目名称" prop="categoryName">
          <el-input v-model="formData.categoryName" placeholder="请输入类目名称" maxlength="50"></el-input>
        </el-form-item>
        
        <el-form-item label="状态" prop="categoryStatus">
          <el-radio-group v-model="formData.categoryStatus">
            <el-radio :label="1" border>启用</el-radio>
            <el-radio :label="0" border>禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
      </div>
    </el-dialog>

    <!-- 删除确认弹窗 -->
    <el-dialog 
      title="确认删除" 
      :visible.sync="deleteDialogVisible" 
      width="400px"
      :close-on-click-modal="false"
    >
      <div class="delete-dialog-content">
        <i class="el-icon-warning-outline warning-icon"></i>
        <div class="delete-text">
          <p class="main-text">
            {{ deleteDialogType === 'single' ? '确定要删除该商品类目吗？' : 
              `确定要删除选中的 ${selectedIds.length} 个商品类目吗？` }}
          </p>
          <p class="sub-text">删除后数据将无法恢复</p>
        </div>
      </div>
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="deleteDialogVisible = false">取消</el-button>
        <el-button 
          type="danger" 
          @click="confirmDelete"
          :loading="deleteLoading"
        >确认删除</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { 
  listCategory, 
  getCategory, 
  addCategory, 
  updateCategory, 
  delCategory,
  batchDelCategory
} from '@/api/product/category';

export default {
  name: 'ProductCategory',
  data() {
    return {
      // 加载状态
      loading: false,
      submitLoading: false,
      deleteLoading: false,
      // 类目列表数据
      categoryList: [],
      // 搜索表单
      searchForm: {
        categoryName: '',
        categoryStatus: ''
      },
      // 类目选项（用于下拉框）
      categoryOptions: [],
      // 分页参数
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      // 选中的ID
      selectedIds: [],
      // 弹窗状态
      dialogVisible: false,
      deleteDialogVisible: false,
      // 弹窗类型：single-单个删除，batch-批量删除
      deleteDialogType: 'single',
      // 弹窗标题
      formTitle: '',
      // 当前操作的ID
      currentId: null,
      // 表单数据
      formData: {
        id: '',
        categoryName: '',
        shopId: '', // 将从Vuex获取
        categoryStatus: 1,
        sortOrder: 0
      },
      // 表单验证规则
      formRules: {
        categoryName: [
          { required: true, message: '请输入类目名称', trigger: 'blur' },
          { max: 50, message: '类目名称不能超过50个字符', trigger: 'blur' }
        ]
      },
      // 权限控制
      hasEditPermission: true,
      hasDeletePermission: true
    };
  },
  computed: {
    // 从Vuex获取店铺ID
    shopId() {
      return this.$store.state.user.shopId;
    }
  },
  watch: {
    // 监听店铺ID变化
    shopId(newVal) {
      if (newVal) {
        this.formData.shopId = newVal;
        this.getCategoryList();
        this.loadCategoryOptions();
      }
    }
  },
  created() {
    this.initPage();
    this.checkPermissions();
  },
  mounted() {
    // 确保店铺ID已设置
    if (this.shopId) {
      this.formData.shopId = this.shopId;
    }
  },
  methods: {
    // 初始化页面
    async initPage() {
      // 等待店铺信息加载
      await this.waitForShopInfo();
      if (this.shopId) {
        this.formData.shopId = this.shopId;
        this.getCategoryList();
        this.loadCategoryOptions();
      }
    },
    
    // 加载类目选项（用于下拉框）
    loadCategoryOptions() {
      if (!this.shopId) return;
      
      const params = {
        pageNum: 1,
        pageSize: 1000, // 获取所有类目
        shopId: this.shopId
      };
      
      listCategory(params).then(response => {
        if (response && response.code === 200) {
          // 将类目列表转换为下拉选项格式
          this.categoryOptions = (response.rows || []).map(item => ({
            value: item.categoryName,
            label: item.categoryName
          }));
        }
      }).catch(error => {
        console.error('加载类目选项失败：', error);
      });
    },
    
    // 等待店铺信息加载
    waitForShopInfo() {
      return new Promise((resolve) => {
        if (this.shopId) {
          resolve();
        } else {
          const checkInterval = setInterval(() => {
            if (this.shopId) {
              clearInterval(checkInterval);
              resolve();
            }
          }, 100);
          
          setTimeout(() => {
            clearInterval(checkInterval);
            resolve();
          }, 5000);
        }
      });
    },
    
    // 获取类目列表
    getCategoryList() {
      if (!this.shopId) {
        this.$message.warning('请先登录并获取店铺信息');
        return;
      }
      
      this.loading = true;
      
      const params = {
        pageNum: this.pagination.currentPage,
        pageSize: this.pagination.pageSize,
        shopId: this.shopId // 添加店铺ID参数
      };
      
      if (this.searchForm.categoryName && this.searchForm.categoryName.trim()) {
        params.categoryName = this.searchForm.categoryName.trim();
      }
      
      if (this.searchForm.categoryStatus !== '') {
        params.categoryStatus = Number(this.searchForm.categoryStatus);
      }
      
      listCategory(params).then(response => {
        this.loading = false;
        if (response && response.code === 200) {
          this.categoryList = response.rows || [];
          this.pagination.total = response.total || 0;
        } else {
          this.$message.error(response?.msg || '获取数据失败');
        }
      }).catch(error => {
        this.loading = false;
        this.$message.error('加载数据失败：' + (error.message || error));
      });
    },
    
    // 搜索
    handleSearch() {
      this.pagination.currentPage = 1;
      this.getCategoryList();
    },
    
    // 重置搜索
    resetSearch() {
      this.searchForm = {
        categoryName: '',
        categoryStatus: ''
      };
      this.pagination.currentPage = 1;
      this.getCategoryList();
    },
    
    // 分页大小改变
    handleSizeChange(pageSize) {
      this.pagination.pageSize = pageSize;
      this.pagination.currentPage = 1;
      this.getCategoryList();
    },
    
    // 当前页改变
    handleCurrentChange(currentPage) {
      this.pagination.currentPage = currentPage;
      this.getCategoryList();
    },
    
    // 处理新增
    handleAdd() {
      if (!this.shopId) {
        this.$message.warning('请先获取店铺信息');
        return;
      }
      
      this.formTitle = '新增商品类目';
      this.currentId = '';
      this.formData = {
        id: '',
        categoryName: '',
        shopId: this.shopId, // 使用当前店铺ID
        categoryStatus: 1,
        sortOrder: 0
      };
      this.dialogVisible = true;
      this.$nextTick(() => {
        if (this.$refs.categoryFormRef) {
          this.$refs.categoryFormRef.resetFields();
        }
      });
    },
    
    // 处理编辑
    handleEdit(row) {
      if (!this.shopId) {
        this.$message.warning('请先获取店铺信息');
        return;
      }
      
      this.formTitle = '编辑商品类目';
      this.currentId = row.id;
      this.dialogVisible = true;
      
      this.$nextTick(() => {
        getCategory(row.id).then(response => {
          if (response && response.code === 200) {
            const data = response.data;
            // 确保只编辑当前店铺的分类
            if (data.shopId !== this.shopId) {
              this.$message.error('无权编辑其他店铺的分类');
              this.dialogVisible = false;
              return;
            }
            
            this.formData = {
              id: data.id,
              categoryName: data.categoryName || '',
              shopId: this.shopId, // 使用当前店铺ID
              categoryStatus: data.categoryStatus !== null ? data.categoryStatus : 1,
              sortOrder: data.sortOrder !== null ? data.sortOrder : 0
            };
          } else {
            this.$message.error('获取数据失败: ' + (response.msg || '未知错误'));
          }
        }).catch(error => {
          this.$message.error('获取数据失败：' + (error.message || error));
        });
      });
    },
    
    // 处理表单提交
    handleSubmit() {
      this.$refs.categoryFormRef.validate(valid => {
        if (valid) {
          if (!this.shopId) {
            this.$message.warning('请先获取店铺信息');
            return;
          }
          
          this.submitLoading = true;
          
          const formData = {
            ...this.formData,
            shopId: this.shopId, // 确保使用当前店铺ID
            sortOrder: this.formData.sortOrder ? Number(this.formData.sortOrder) : 0,
            categoryStatus: Number(this.formData.categoryStatus)
          };
          
          let requestPromise;
          if (this.currentId) {
            // 编辑类目
            requestPromise = updateCategory(formData);
          } else {
            // 新增类目
            requestPromise = addCategory(formData);
          }
          
          requestPromise.then((response) => {
            this.submitLoading = false;
            if (response && response.code === 200) {
              this.$message.success(this.currentId ? '修改成功' : '新增成功');
              this.dialogVisible = false;
              this.getCategoryList();
              // 新增或编辑成功后重新加载下拉选项
              this.loadCategoryOptions();
            } else {
              this.$message.error(response?.msg || '操作失败');
            }
          }).catch(error => {
            this.submitLoading = false;
            this.$message.error(`${this.currentId ? '修改' : '新增'}失败：` + (error.message || error));
          });
        }
      });
    },
    
    // 处理单个删除
    handleDelete(id) {
      if (!this.shopId) {
        this.$message.warning('请先获取店铺信息');
        return;
      }
      
      this.currentId = id;
      this.deleteDialogType = 'single';
      this.deleteDialogVisible = true;
    },
    
    // 处理批量删除
    handleBatchDelete() {
      if (!this.shopId) {
        this.$message.warning('请先获取店铺信息');
        return;
      }
      
      if (this.selectedIds.length === 0) {
        this.$message.warning('请先选择要删除的类目');
        return;
      }
      this.deleteDialogType = 'batch';
      this.deleteDialogVisible = true;
    },
    
    // 确认删除
    confirmDelete() {
      this.deleteLoading = true;
      let requestPromise;
      
      if (this.deleteDialogType === 'single') {
        requestPromise = delCategory(this.currentId);
      } else {
        requestPromise = batchDelCategory(this.selectedIds);
      }
      
      requestPromise.then((response) => {
        this.deleteLoading = false;
        if (response && response.code === 200) {
          this.$message.success('删除成功');
          this.deleteDialogVisible = false;
          this.selectedIds = [];
          this.getCategoryList();
          // 删除成功后重新加载下拉选项
          this.loadCategoryOptions();
        } else {
          this.$message.error(response?.msg || '删除失败');
        }
      }).catch(error => {
        this.deleteLoading = false;
        this.$message.error('删除失败：' + (error.message || error));
      });
    },
    
    // 处理状态变更
    handleStatusChange(row) {
      if (!this.shopId) {
        this.$message.warning('请先获取店铺信息');
        return;
      }
      
      const originalStatus = row.categoryStatus;
      const newStatus = row.categoryStatus === 1 ? 0 : 1;
      const statusText = newStatus === 1 ? '启用' : '禁用';
      
      this.$confirm(`确定要${statusText}该商品类目吗？`, '确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        updateCategory({
          id: row.id,
          categoryStatus: newStatus,
          shopId: this.shopId // 确保使用当前店铺ID
        }).then((response) => {
          if (response && response.code === 200) {
            row.categoryStatus = newStatus;
            this.$message.success(`状态已${statusText}`);
          } else {
            row.categoryStatus = originalStatus;
            this.$message.error(response?.msg || `状态${statusText}失败`);
          }
        }).catch(error => {
          row.categoryStatus = originalStatus;
          this.$message.error(`状态${statusText}失败：` + (error.message || error));
        });
      }).catch(() => {
        row.categoryStatus = originalStatus;
      });
    },
    
    // 处理选择变更
    handleSelectionChange(selection) {
      this.selectedIds = selection.map(row => row.id);
    },
    
    // 表格行样式
    tableRowClassName({ row, rowIndex }) {
      return rowIndex % 2 === 1 ? 'even-row' : 'odd-row';
    },
    
    // 检查权限
    checkPermissions() {
      this.hasEditPermission = true;
      this.hasDeletePermission = true;
    }
  }
};
</script>

<style scoped>
/* 样式保持不变 */
.product-category-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 84px);
}

.page-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  margin-bottom: 20px;
  border-radius: 10px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  color: white;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
}

.page-header h2 {
  margin: 0;
  font-size: 22px;
  font-weight: 600;
  display: flex;
  align-items: center;
}

.page-header h2 i {
  margin-right: 10px;
  font-size: 24px;
}

.shop-info {
  display: flex;
  align-items: center;
  gap: 15px;
}

.product-count {
  color: rgba(255, 255, 255, 0.9);
  font-size: 14px;
}

.search-container {
  padding: 20px;
  background: white;
  border-radius: 10px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  margin-bottom: 20px;
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  align-items: center;
}

.search-input {
  width: 200px;
}

.action-buttons {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
  border-top: 1px dashed #e8e8e8;
  padding-top: 15px;
}

.btn-add {
  margin-left: 0;
}

.table-container {
  padding: 20px;
  background: white;
  border-radius: 10px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  margin-bottom: 20px;
  overflow: hidden;
}

.pagination-container {
  padding: 15px 20px;
  background: white;
  border-radius: 10px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  text-align: right;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.delete-dialog-content {
  display: flex;
  align-items: center;
  gap: 15px;
}

.warning-icon {
  font-size: 24px;
  color: #e6a23c;
}

.delete-text .main-text {
  margin: 0 0 5px 0;
  font-weight: 500;
}

.delete-text .sub-text {
  margin: 0;
  color: #909399;
  font-size: 13px;
}

.disabled-state {
  opacity: 0.6;
  pointer-events: none;
}

.category-name {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 5px;
}

.mb-4 {
  margin-bottom: 20px;
}
</style>